package com.toKnow.controller;


import com.toKnow.model.entity.*;
import com.toKnow.model.vo.BasicVo;
import com.toKnow.model.vo.ThreeReturn;
import com.toKnow.model.vo.SourcePubOV;
import com.toKnow.service.ResourcePubService;
import com.toKnow.service.SourceService;
import com.toKnow.service.TypeTagPubService;
import com.toKnow.utils.JwtUserSessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping("/api")
public class ResourcePubController {

    @Autowired
    private ResourcePubService resourcePubService;
    @Autowired
    private TypeTagPubService typeTagPubService;

    @Autowired
    private SourceService sourceService;

    public void setResourcePubService(ResourcePubService resourcePubService) {
        this.resourcePubService = resourcePubService;
    }

    public void setTypeTagPubService(TypeTagPubService typeTagPubService) {
        this.typeTagPubService = typeTagPubService;
    }

    private Integer getUid(HttpSession session) {
        String userToken = (String) session.getAttribute("userToken");
        String user_id_string = JwtUserSessionUtil.getInfo(userToken,"id");
        if(user_id_string == null) {
            return -1;
        } else {
            return Integer.valueOf(user_id_string);
        }
    }

    @RequestMapping(value = "/source/content/submit",method = RequestMethod.POST)
    @ResponseBody
    public SourcePubOV addResource(HttpServletRequest request,
                                   Integer upload_date, String title, MultipartFile file,
                                   Integer is_charged, Float price,
                                   String type, String tag,
                                   MultipartFile cover,String digest){

        SourcePubOV sourcePubOV =new SourcePubOV();

        String source_name = file.getOriginalFilename();

        HttpSession session = request.getSession();

        Integer user_id = getUid(session);
        if (user_id == -1) {
            sourcePubOV.setSuccess(false);
            sourcePubOV.setMessage("请先登录");
            return sourcePubOV;
        }

        //处理file
        String filePath = null;
        if(file != null && file.getSize() != 0) {
            //获取文件的后缀名
            int lastIndexOf = Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(".");
            String suffix;
            if(lastIndexOf != -1) {
                suffix = file.getOriginalFilename().substring(lastIndexOf);
            } else {
                suffix = "";
            }
            //根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
            String fileName = System.currentTimeMillis() + suffix;
            //获取当前项目的真实路径，然后拼接前面的文件
            String destFileName = request.getServletContext().getRealPath("")
                + "static"
                + File.separator
                + "source"
                + File.separator
                + fileName;
            //第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下static/user_source文件夹下）
            File destFile = new File(destFileName);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            //把浏览器上传的文件复制到希望的位置
            try {
                file.transferTo(destFile);
            } catch ( IOException e) {
                return null;
            }

            filePath = File.separator
                + "static"
                + File.separator
                + "source"
                + File.separator
                + fileName;
        }else {
            filePath =null;
        }

        //处理cover
        String coverPath = null;
        if(cover != null && cover.getSize() != 0) {
            //获取文件的后缀名
            int lastIndexOf = Objects.requireNonNull(cover.getOriginalFilename()).lastIndexOf(".");
            String suffix;
            if(lastIndexOf != -1) {
                suffix = cover.getOriginalFilename().substring(lastIndexOf);
            } else {
                suffix = "";
            }
            //根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
            String fileName = System.currentTimeMillis() + suffix;
            //获取当前项目的真实路径，然后拼接前面的文件
            String destFileName = request.getServletContext().getRealPath("")
                + "static"
                + File.separator
                + "source_cover"
                + File.separator
                + fileName;
            //第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下static/user_source文件夹下）
            File destFile = new File(destFileName);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            //把浏览器上传的文件复制到希望的位置
            try {
                cover.transferTo(destFile);
            } catch ( IOException e) {
                return null;
            }


            coverPath = File.separator +
                "static"
                + File.separator
                + "source_cover"
                + File.separator
                + fileName;
        }else {
            coverPath =null;
        }

        //将type tag  name 转化为id
        List<String> type1 =null;
        List<String> tag1 = null;

        if(tag!=null ){
            tag1 = Arrays.asList(tag.split(","));
        }
        if(type!=null){
            type1 = Arrays.asList(type.split(","));
        }

        List<Integer> types  = typeTagPubService.convertTypeNameToId(type1);
        List<Integer> tags = typeTagPubService.convertTagNameToId(tag1);

        //插入source表
        ResourcePub resourcePub = new ResourcePub();
        resourcePub.setTitle(title);
        resourcePub.setAuthor_id(user_id);
        resourcePub.setPrice(price);
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        resourcePub.setPublish_date(ts);
        resourcePub.setFile(filePath);
        if(is_charged==1){
            resourcePub.setIs_charged(1);
        }else {
            resourcePub.setIs_charged(0);
        }
        resourcePub.setCover(coverPath);
        resourcePub.setDigest(digest);
        resourcePub.setSource_name(source_name);
        resourcePub.setTagIds(tags);
        resourcePub.setTypeIds(types);

        //修改用户发布资源数
        UserInfoPub userInfoPub = new UserInfoPub();
        userInfoPub.setId(user_id);

        Integer source_id = resourcePubService.addResource(resourcePub,userInfoPub);

        sourcePubOV.setSuccess(true);
        sourcePubOV.setMessage("success");
        sourcePubOV.setSource_id(String.valueOf(source_id));

        return sourcePubOV;

    }

    @RequestMapping(value = "/source/content/store",method = RequestMethod.POST)
    @ResponseBody
    public SourcePubOV storeResource(HttpServletRequest request,
                                   Integer upload_date, String title, MultipartFile file,
                                   Integer is_charged, Float price,
                                   String type, String tag,
                                   MultipartFile cover,String digest){

        SourcePubOV sourcePubOV =new SourcePubOV();

        String source_name = file.getOriginalFilename();

        HttpSession session = request.getSession();

        Integer user_id = getUid(session);
        if (user_id == -1) {
            sourcePubOV.setSuccess(false);
            sourcePubOV.setMessage("请先登录");
            return sourcePubOV;
        }

        //处理file
        String filePath = null;
        if(file != null && file.getSize() != 0) {
            //获取文件的后缀名
            int lastIndexOf = Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(".");
            String suffix;
            if(lastIndexOf != -1) {
                suffix = file.getOriginalFilename().substring(lastIndexOf);
            } else {
                suffix = "";
            }
            //根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
            String fileName = System.currentTimeMillis() + suffix;
            //获取当前项目的真实路径，然后拼接前面的文件
            String destFileName = request.getServletContext().getRealPath("")
                + "static"
                + File.separator
                + "source_draft"
                + File.separator
                + fileName;
            //第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下static/user_source文件夹下）
            File destFile = new File(destFileName);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            //把浏览器上传的文件复制到希望的位置
            try {
                file.transferTo(destFile);
            } catch ( IOException e) {
                return null;
            }

            filePath = File.separator
                + "static"
                + File.separator
                + "source_draft"
                + File.separator
                + fileName;
        }else {
            filePath =null;
        }

        //处理cover
        String coverPath = null;
        if(cover != null && cover.getSize() != 0) {
            //获取文件的后缀名
            int lastIndexOf = Objects.requireNonNull(cover.getOriginalFilename()).lastIndexOf(".");
            String suffix;
            if(lastIndexOf != -1) {
                suffix = cover.getOriginalFilename().substring(lastIndexOf);
            } else {
                suffix = "";
            }
            //根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
            String fileName = System.currentTimeMillis() + suffix;
            //获取当前项目的真实路径，然后拼接前面的文件
            String destFileName = request.getServletContext().getRealPath("")
                + "static"
                + File.separator
                + "source_draft_cover"
                + File.separator
                + fileName;
            //第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下static/user_source文件夹下）
            File destFile = new File(destFileName);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            //把浏览器上传的文件复制到希望的位置
            try {
                cover.transferTo(destFile);
            } catch ( IOException e) {
                return null;
            }

            coverPath = File.separator +
                "static"
                + File.separator
                + "source_draft_cover"
                + File.separator
                + fileName;
        }else {
            coverPath =null;
        }

        //将type tag  name 转化为id
        List<String> type1 =null;
        List<String> tag1 = null;

        if(tag!=null ){
            tag1 = Arrays.asList(tag.split(","));
        }
        if(type!=null){
            type1 = Arrays.asList(type.split(","));
        }

        List<Integer> types  = typeTagPubService.convertTypeNameToId(type1);
        List<Integer> tags = typeTagPubService.convertTagNameToId(tag1);

        //插入source表
        ResourcePub resourcePub = new ResourcePub();
        resourcePub.setTitle(title);
        resourcePub.setAuthor_id(user_id);
        resourcePub.setPrice(price);
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        resourcePub.setPublish_date(ts);
        resourcePub.setFile(filePath);
        if(is_charged==1){
            resourcePub.setIs_charged(1);
        }else {
            resourcePub.setIs_charged(0);
        }
        resourcePub.setCover(coverPath);
        resourcePub.setDigest(digest);
        resourcePub.setSource_name(source_name);
        resourcePub.setTagIds(tags);
        resourcePub.setTypeIds(types);

        //修改用户发布资源数
        UserInfoPub userInfoPub = new UserInfoPub();
        userInfoPub.setId(user_id);

        Integer source_id = resourcePubService.storeResource(resourcePub,userInfoPub);

        sourcePubOV.setSuccess(true);
        sourcePubOV.setMessage("success");
        sourcePubOV.setSource_id(String.valueOf(source_id));


        return sourcePubOV;

    }

    @RequestMapping(value = "/source/content/draft/update",method = RequestMethod.POST)
    @ResponseBody
    public SourcePubOV updateResourceDraft(HttpServletRequest request, Integer draft_id,
                                     Integer upload_date, String title, MultipartFile file,
                                     Integer is_charged, Float price,
                                     String type, String tag,
                                     MultipartFile cover,String digest){

        HttpSession session = request.getSession();

        SourcePubOV sourcePubOV =new SourcePubOV();

        Integer user_id = getUid(session);
        if (user_id == -1) {
            sourcePubOV.setSuccess(false);
            sourcePubOV.setMessage("请先登录");
            return sourcePubOV;
        }

        if(draft_id == null) {
            sourcePubOV.setSuccess(false);
            sourcePubOV.setMessage("未携带草稿编号");
            return sourcePubOV;
        }

        Source draftSource = sourceService.selectSourceDraftById(user_id, draft_id);

        String draftCoverPathPart = draftSource.getCover();
        if(draftCoverPathPart != null){
            String draftCoverPath = request.getServletContext().getRealPath("")
                + draftCoverPathPart;
            File delCover = new File(draftCoverPath);
            delCover.delete();
        }

        String draftFilePathPart = draftSource.getFile();
        if(draftFilePathPart != null) {
            String draftFilePath = request.getServletContext().getRealPath("")
                + draftFilePathPart;
            File delFile = new File(draftFilePath);
            delFile.delete();
        }

        String source_name = file.getOriginalFilename();

        //处理file
        String filePath = null;
        if(file != null && file.getSize() != 0) {
            //获取文件的后缀名
            int lastIndexOf = Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(".");
            String suffix;
            if(lastIndexOf != -1) {
                suffix = file.getOriginalFilename().substring(lastIndexOf);
            } else {
                suffix = "";
            }
            //根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
            String fileName = System.currentTimeMillis() + suffix;
            //获取当前项目的真实路径，然后拼接前面的文件
            String destFileName = request.getServletContext().getRealPath("")
                + "static"
                + File.separator
                + "source_draft"
                + File.separator
                + fileName;
            //第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下static/user_source文件夹下）
            File destFile = new File(destFileName);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            //把浏览器上传的文件复制到希望的位置
            try {
                file.transferTo(destFile);
            } catch ( IOException e) {
                return null;
            }

            filePath = File.separator
                + "static"
                + File.separator
                + "source_draft"
                + File.separator
                + fileName;
        }else {
            filePath =null;
        }

        //处理cover
        String coverPath = null;
        if(cover != null && cover.getSize() != 0) {
            //获取文件的后缀名
            int lastIndexOf = Objects.requireNonNull(cover.getOriginalFilename()).lastIndexOf(".");
            String suffix;
            if(lastIndexOf != -1) {
                suffix = cover.getOriginalFilename().substring(lastIndexOf);
            } else {
                suffix = "";
            }
            //根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
            String fileName = System.currentTimeMillis() + suffix;
            //获取当前项目的真实路径，然后拼接前面的文件
            String destFileName = request.getServletContext().getRealPath("")
                + "static"
                + File.separator
                + "source_draft_cover"
                + File.separator
                + fileName;
            //第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下static/user_source文件夹下）
            File destFile = new File(destFileName);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            //把浏览器上传的文件复制到希望的位置
            try {
                cover.transferTo(destFile);
            } catch ( IOException e) {
                return null;
            }

            coverPath = File.separator +
                "static"
                + File.separator
                + "source_draft_cover"
                + File.separator
                + fileName;
        }else {
            coverPath =null;
        }

        //将type tag  name 转化为id
        List<String> type1 =null;
        List<String> tag1 = null;

        if(tag!=null ){
            tag1 = Arrays.asList(tag.split(","));
        }
        if(type!=null){
            type1 = Arrays.asList(type.split(","));
        }

        List<Integer> types  = typeTagPubService.convertTypeNameToId(type1);
        List<Integer> tags = typeTagPubService.convertTagNameToId(tag1);

        //插入source表
        ResourcePub resourcePub = new ResourcePub();
        resourcePub.setTitle(title);
        resourcePub.setAuthor_id(user_id);
        resourcePub.setPrice(price);
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        resourcePub.setPublish_date(ts);
        resourcePub.setFile(filePath);
        if(is_charged==1){
            resourcePub.setIs_charged(1);
        }else {
            resourcePub.setIs_charged(0);
        }
        resourcePub.setCover(coverPath);
        resourcePub.setDigest(digest);
        resourcePub.setSource_name(source_name);
        resourcePub.setTagIds(tags);
        resourcePub.setTypeIds(types);

        //修改用户发布资源数
        UserInfoPub userInfoPub = new UserInfoPub();
        userInfoPub.setId(user_id);

        Integer source_id = resourcePubService.updateResourceDraft(draft_id, resourcePub,userInfoPub);

        sourcePubOV.setSuccess(true);
        sourcePubOV.setMessage("success");
        sourcePubOV.setSource_id(String.valueOf(source_id));


        return sourcePubOV;

    }

    @RequestMapping(value = "/source/content/comment/submit", method = RequestMethod.POST)
    @ResponseBody
    public BasicVo commentResource(HttpSession session, Integer date, String content, Integer source_id) {
        BasicVo cm = new BasicVo(false, "", null);

        Integer user_id = getUid(session);
        if (user_id == -1) {
            cm.setMessage("请先登录");
            return cm;
        }

        Integer author_id = resourcePubService.findAuthor(source_id);

        ResourceCommentPub resourceCommentPub = new ResourceCommentPub();
        resourceCommentPub.setUser_id(user_id);
        resourceCommentPub.setResource_id(source_id);
        resourceCommentPub.setContent(content);
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        resourceCommentPub.setComment_date(ts);

        UserInfoPub userInfoPub = new UserInfoPub();
        userInfoPub.setId(author_id);


        int i = resourcePubService.commentResource(resourceCommentPub, userInfoPub, source_id);

        if (i == 1) {
            cm.setSuccess(true);
            cm.setMessage("success");
        } else {
            cm.setSuccess(false);
            cm.setMessage("false");
        }
        return cm;

    }

    @RequestMapping(value = "/source/content/comment/reply/submit",method = RequestMethod.POST)
    @ResponseBody
    public ThreeReturn answerResourceComment(Integer user_id,Integer date,String content,Integer comment_id){

        //若前端不提供 user_id 则 从token 中获取
        //String userToken = (String) request.getSession().getAttribute("userToken");
        //Integer user_id = Integer.valueOf( JwtUserSessionUtil.getInfo(userToken,"id") );

        ResourceCommentAnswerPub resourceCommentAnswerPub = new ResourceCommentAnswerPub();
        resourceCommentAnswerPub.setUser_id(user_id);
        resourceCommentAnswerPub.setResource_comment_id(comment_id);

        resourceCommentAnswerPub.setContent(content);
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        resourceCommentAnswerPub.setAnswer_date(ts);

        int i = resourcePubService.answerResourceComment(resourceCommentAnswerPub);

        ThreeReturn threeReturn = new ThreeReturn();

        if(i==1){
            threeReturn.setSuccess(true);
            threeReturn.setMessage("success");
        }else {
            threeReturn.setSuccess(false);
            threeReturn.setMessage("false");
        }
        return threeReturn;

    }


    @RequestMapping(value = "/source/content/like",method = RequestMethod.POST)
    @ResponseBody
    public BasicVo likeResource(HttpSession session, Integer source_id){

        BasicVo cm = new BasicVo(false, "", null);

        Integer user_id = getUid(session);
        if (user_id == -1) {
            cm.setMessage("请先登录");
            return cm;
        }

        Integer author_id = resourcePubService.findAuthor(source_id);
        ResourceLikePub resourceLikePub = new ResourceLikePub();
        resourceLikePub.setResource_id(source_id);
        resourceLikePub.setUser_id(user_id);
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        resourceLikePub.setLike_date(ts);

        int i=resourcePubService.likeResource(resourceLikePub,author_id,source_id);

        if(i==1){
            cm.setSuccess(true);
            cm.setMessage("success like");
        }else if(i==2){
            cm.setSuccess(true);
            cm.setMessage("success unlike");
        }else {
            cm.setSuccess(false);
            cm.setMessage("false");
        }
        return cm;

    }


    @RequestMapping(value = "/source/content/comment/like" , method = RequestMethod.POST)
    @ResponseBody
    public ThreeReturn likeResourceComment(Integer comment_id,Integer user_id){

        //若前端不提供 user_id 则 从token 中获取
        //String userToken = (String) request.getSession().getAttribute("userToken");
        //Integer user_id = Integer.valueOf( JwtUserSessionUtil.getInfo(userToken,"id") );

        ResourceCommentLikePub resourceCommentLikePub = new ResourceCommentLikePub();
        resourceCommentLikePub.setUser_id(user_id);
        resourceCommentLikePub.setComment_resource_id(comment_id);

        int i = resourcePubService.likeComment(resourceCommentLikePub,comment_id);
        ThreeReturn threeReturn = new ThreeReturn();

        if(i==1){
            threeReturn.setSuccess(true);
            threeReturn.setMessage("success like");
        }else if(i==2) {
            threeReturn.setSuccess(true);
            threeReturn.setMessage("success unlike");
        }else {
            threeReturn.setSuccess(false);
            threeReturn.setMessage("false");
        }
        return threeReturn;

    }

    @RequestMapping(value = "/source/content/comment/reply/like",method = RequestMethod.POST)
    @ResponseBody
    public ThreeReturn likeResourceAnswer(Integer reply_id,Integer user_id){

        //若前端不提供 user_id 则 从token 中获取
        //String userToken = (String) request.getSession().getAttribute("userToken");
        //Integer user_id = Integer.valueOf( JwtUserSessionUtil.getInfo(userToken,"id") );

        ResourceAnswerLikePub resourceAnswerLikePub = new ResourceAnswerLikePub();
        resourceAnswerLikePub.setUser_id(user_id);
        resourceAnswerLikePub.setAnswer_resource_id(reply_id);

       int i =  resourcePubService.likeAnswer(resourceAnswerLikePub,reply_id);
        ThreeReturn threeReturn = new ThreeReturn();

        if(i==1){
            threeReturn.setSuccess(true);
            threeReturn.setMessage("success like");
        }else if(i==2){
            threeReturn.setSuccess(true);
            threeReturn.setMessage("success unlike");
        }else {
            threeReturn.setSuccess(false);
            threeReturn.setMessage("false");
        }
        return threeReturn;

    }

}
